<?php

/* Note: This thumbnail creation script requires the GD PHP Extension.  
  If GD is not installed correctly PHP does not render this page correctly
  and SWFUpload will get "stuck" never calling uploadSuccess or uploadError
 */

// Get the session Id passed from SWFUpload. We have to do this to work-around the Flash Player Cookie Bug
if (isset($_POST["PHPSESSID"])) {
    session_id($_POST["PHPSESSID"]);
}

session_start();
ini_set("html_errors", "0");

//Set response
$response = array(
    'error'     =>  1,
    'message'   =>  'ERROR'
);

// Check the upload
if (!isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) {
    $response['message'] =  "ERROR:invalid upload";
    echo json_encode($response); exit(0);
}

//Get File extension
$fileExt = strtolower(substr($_FILES['Filedata']['name'], -4));
$fileName = md5($_FILES['Filedata']['name']);
$tempFile = $_FILES['Filedata']['tmp_name'];

//Check folder
$folder = isset($_POST['folder'])?$_POST['folder']:'/uploads/videos/';

//Make dir
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $folder . date('Y') . '/';
if (!is_dir($targetPath)) {
    mkdir(str_replace('//', '/', $targetPath), 0777, true);
}
$targetPath.= date('m') . '/';
if (!is_dir($targetPath)) {
    mkdir(str_replace('//', '/', $targetPath), 0777, true);
}
$targetPath.= date('d') . '/';
if (!is_dir($targetPath)) {
    mkdir(str_replace('//', '/', $targetPath), 0777, true);
}
$targetFile =  str_replace('//','/',$targetPath) . $fileName . $fileExt;

//Move file from tmp to folder upload
move_uploaded_file($tempFile, $targetFile);

//Set response
$response = array(
    'error'     =>  0,
    'message'   =>  'success',
    'body'      =>  array(
        'FILEID'    =>  $_POST["PHPSESSID"],
        'FILEURL'   => str_replace($_SERVER['DOCUMENT_ROOT'], '', $targetPath . $fileName . $fileExt), 
        'THUMBURL'  => ''
    )
);

//Return response
echo json_encode($response); exit(0);

?>